// 一个简单的X11中OpenGL测试程序，测试OpenGL和软件渲染的性能差异

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <GL/gl.h>
#include <GL/glx.h>
#include <math.h>

// 定义数学常量
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

Display *display;
Window win;
GLXContext glContext;

// FPS 相关变量
static int frame_count = 0;
static double last_time = 0.0;
static double current_fps = 0.0;
static int test_mode = 1;           // 测试模式：1=OpenGL简单三角形, 2=OpenGL压力测试, 3=软件渲染简单, 4=软件渲染压力测试, 5=OpenGL立方体, 6=软件立方体
static int vsync_enabled = 1;       // VSync控制：1=启用, 0=禁用

// 文字渲染相关变量
static char fps_text[256] = "";
static char mode_text[256] = "";
static char vsync_text[256] = "";
static char renderer_text[512] = "";
static char rendering_type_text[256] = "";

#define  _packed  __attribute__((packed))

typedef struct bgra {
    unsigned char b, g, r, a;
}  _packed bgra_t;  // BGRA颜色格式

typedef bgra_t color_t;  // 定义颜色类型
typedef color_t pixel_t; // 定义像素类型，用于软件渲染

typedef struct {
    int x, y;
    color_t color;
} _packed vertex_t;  // 顶点结构体，用于软件渲染三角形


// 软件渲染相关变量
static pixel_t *frame_buffer = NULL;
static int win_width, win_height;         // 窗口宽度和高度

// 函数声明
void clear_buffer(void);
void render_triangle_software(vertex_t v1, vertex_t v2, vertex_t v3);
void render_software_simple(void);
void render_software_stress_test(void);

void update_fps_and_mode_text(void);
void render_ui_text(void);

static const color_t RED =    {.b=0,    .g= 0,    .r=255};
static const color_t GREEN =  {.b=0,    .g=255,   .r=0};
static const color_t BLUE =   {.b=255,  .g=0,     .r=0};

// 获取当前时间（秒）
static double get_time() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

// 显示系统信息用于调试
void print_system_info() {

    printf("=== 系统显示信息 ===\n");
    printf("=== OpenGL 渲染信息 ===\n");
    
    // 检查OpenGL上下文是否有效
    if (!glContext) {
        printf("❌ OpenGL上下文无效\n");
        printf("===================\n");
        snprintf(renderer_text, sizeof(renderer_text), "RENDERER: OpenGL Context Invalid");
        snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Context Error");
        return;
    }
    
    // 检查当前上下文
    GLXContext current = glXGetCurrentContext();
    if (!current) {
        printf("❌ 没有当前OpenGL上下文\n");
        printf("===================\n");
        snprintf(renderer_text, sizeof(renderer_text), "RENDERER: No Current Context");
        snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Context Error");
        return;
    }
    
    const char* renderer = (const char*)glGetString(GL_RENDERER);
    const char* vendor = (const char*)glGetString(GL_VENDOR);
    const char* version = (const char*)glGetString(GL_VERSION);
    
    printf("渲染器: %s\n", renderer ? renderer : "❌ 无法获取");
    printf("厂商: %s\n", vendor ? vendor : "❌ 无法获取");
    printf("版本: %s\n", version ? version : "❌ 无法获取");
    
    // 更新渲染器文本
    if (renderer) {
        snprintf(renderer_text, sizeof(renderer_text), "RENDERER: %s", renderer);
    } else {
        snprintf(renderer_text, sizeof(renderer_text), "RENDERER: Unknown");
    }
    
    int is_cpu = renderer && (strstr(renderer, "llvmpipe") || strstr(renderer, "softpipe") || strstr(renderer, "swrast"));
    int is_direct = glXIsDirect(display, glContext);
    if (is_cpu) {
        printf("🔧 检测到软件渲染器\n");
        printf("  - 使用CPU进行OpenGL渲染\n");
        printf("  - 这可能是驱动问题导致的\n");
        if (is_direct) {
            printf("  - 直接渲染 (CPU执行)\n");
            snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Direct (CPU)");
        } else {
            printf("  - 间接渲染 (CPU执行)\n");
            snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Indirect (CPU)");
        }
    } else {
        if (is_direct) {
            printf("✓ 使用直接渲染 (本地GPU执行)\n");
            printf("  - OpenGL命令直接在本地GPU上执行\n");
            printf("  - 性能最佳，延迟最低\n");
            snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Direct (GPU)");
        } else {
            printf("⚠ 使用间接渲染 (X11 Server执行)\n");
            printf("  - OpenGL命令发送给X11 Server执行\n");
            printf("  - 可能存在网络延迟，性能较低\n");
            snprintf(rendering_type_text, sizeof(rendering_type_text), "RENDERING: Indirect (GPU)");
        }
    }
}

// 初始化 X11 窗口和 OpenGL 上下文
void initXWindow(int width, int height) {
    // 1. 打开 X 显示连接
    display = XOpenDisplay(NULL);
    if (!display) {
        fprintf(stderr, "❌ 无法打开 X 显示\n");
        fprintf(stderr, "检查事项:\n");
        fprintf(stderr, "  - 确保X11服务正在运行\n");
        fprintf(stderr, "  - 检查DISPLAY环境变量: %s\n", getenv("DISPLAY") ? getenv("DISPLAY") : "未设置");
        exit(1);
    }

    int screen = DefaultScreen(display);

    // 显示屏幕信息
    printf("✓ 屏幕宽度: %d, 高度:%d, DPI: %.1f\n", DisplayWidth(display, screen) , DisplayHeight(display, screen), DisplayWidthMM(display, screen) / 25.4);
    printf("  -颜色深度: %d bits\n",  DefaultDepth(display, screen));

    // 2. 检查GLX扩展
    int glx_major, glx_minor;
    if (!glXQueryVersion(display, &glx_major, &glx_minor)) {
        fprintf(stderr, "❌ GLX扩展不可用\n");
        exit(1);
    }
    printf("✓ GLX版本: %d.%d\n", glx_major, glx_minor);

    // 3. 尝试多种视觉配置
    XVisualInfo *vi = NULL;
    
    // 首先尝试硬件加速配置
    static int hw_attribs[] = {
        GLX_RGBA,
        GLX_DOUBLEBUFFER,
        GLX_RED_SIZE, 8,
        GLX_GREEN_SIZE, 8,
        GLX_BLUE_SIZE, 8,
        GLX_DEPTH_SIZE, 24,
        None
    };
    vi = glXChooseVisual(display, screen, hw_attribs);
    
    if (!vi) {
        printf("⚠ 硬件加速配置失败，尝试基本配置...\n");
        // 尝试更简单的配置
        static int basic_attribs[] = {
            GLX_RGBA,
            GLX_RED_SIZE, 1,
            GLX_GREEN_SIZE, 1,
            GLX_BLUE_SIZE, 1,
            None
        };
        vi = glXChooseVisual(display, screen, basic_attribs);
    }
    
    if (!vi) {
        fprintf(stderr, "❌ 找不到任何合适的视觉配置\n");
        fprintf(stderr, "可能的解决方案:\n");
        fprintf(stderr, "  - 安装Mesa OpenGL库: sudo apt install mesa-utils libgl1-mesa-glx\n");
        fprintf(stderr, "  - 安装软件渲染支持: sudo apt install mesa-utils-extra\n");
        fprintf(stderr, "  - 检查显卡驱动是否正确安装\n");
        exit(1);
    }
    
    printf("✓ 找到合适的视觉配置 (ID: 0x%lx)\n", vi->visualid);
    printf("  - 颜色深度: %d bits\n", vi->depth);
    printf("  - 颜色模式: %s\n", vi->class == TrueColor ? "TrueColor" : "其他");
    printf("  - 颜色掩码: 红 0x%lx, 绿 0x%lx, 蓝 0x%lx\n", vi->red_mask, vi->green_mask, vi->blue_mask);


    // 4. 创建 X 窗口
    Colormap cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
    XSetWindowAttributes swa;
    swa.colormap = cmap;
    swa.border_pixel = 0;
    swa.event_mask = ExposureMask | KeyPressMask;

    win = XCreateWindow(display, RootWindow(display, vi->screen),
                        0, 0, width, height, 0,
                        vi->depth, InputOutput, vi->visual,
                        CWBorderPixel | CWColormap | CWEventMask, &swa);

    XStoreName(display, win, "OpenGL vs Software Rendering Performance Test");
    XMapWindow(display, win);

    // 5. 创建 OpenGL 上下文
    glContext = glXCreateContext(display, vi, NULL, GL_TRUE);
    if (!glContext) {
        fprintf(stderr, "❌ 无法创建OpenGL上下文\n");
        exit(1);
    }
    
    if (!glXMakeCurrent(display, win, glContext)) {
        fprintf(stderr, "❌ 无法激活OpenGL上下文\n");
        exit(1);
    }
    
    printf("✓ OpenGL上下文创建成功\n");
}

// 字节序检测
void detect_byte_order(Display *display) {
    // 检测X Server字节序
    int server_byte_order = ImageByteOrder(display);
    
    // 检测本地字节序
    int local_little_endian = 1;
    union { unsigned int i; unsigned char c[4]; } test = { 1 };
    local_little_endian = test.c[0];
    
    printf("=== 字节序检测结果 ===\n");
    printf("X Server字节序: %s\n", 
           server_byte_order == LSBFirst ? "小端序(LSB First)" : "大端序(MSB First)");
    printf("本地机器字节序: %s\n", 
           local_little_endian ? "小端序" : "大端序");
    
    if ((server_byte_order == LSBFirst) == local_little_endian) {
        printf("字节序匹配，无需转换\n");
    } else {
        printf("字节序不匹配，需要进行字节转换\n");
    }
}

// OpenGL 初始化
void initGL() {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 黑色背景
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); // 简单正交投影
}

// 检查是否支持VSync控制
int check_vsync_support() {
    const char* glx_ext = glXQueryExtensionsString(display, DefaultScreen(display));
    
    if (strstr(glx_ext, "GLX_EXT_swap_control")) {
        printf("✓ Detected GLX_EXT_swap_control extension\n");
        return 1;
    }
    
    if (strstr(glx_ext, "GLX_MESA_swap_control")) {
        printf("✓ Detected GLX_MESA_swap_control extension\n");
        return 1;
    }
    
    if (strstr(glx_ext, "GLX_SGI_swap_control")) {
        printf("✓ Detected GLX_SGI_swap_control extension\n");
        return 1;
    }
    
    printf("⚠ No VSync control extensions found\n");
    printf("Available extensions: %s\n", glx_ext ? glx_ext : "None");
    return 0;
}

// 控制垂直同步状态
void set_vsync(int enable) {
    // 先检查是否支持VSync控制
    if (!check_vsync_support()) {
        printf("❌ VSync control not supported on this system\n");
        printf("Try using environment variable: vblank_mode=%d ./x11-glx-test\n", enable ? 1 : 0);
        return;
    }
    
    const char* glx_ext = glXQueryExtensionsString(display, DefaultScreen(display));
    printf("=== %s VSync ===\n", enable ? "Enabling" : "Disabling");
    
    // 检查并尝试使用 GLX_EXT_swap_control
    if (strstr(glx_ext, "GLX_EXT_swap_control")) {
        typedef int (*PFNGLXSWAPINTERVALEXTPROC)(Display*, GLXDrawable, int);
        PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = 
            (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddress((const GLubyte*)"glXSwapIntervalEXT");
        if (glXSwapIntervalEXT) {
            int result = glXSwapIntervalEXT(display, win, enable ? 1 : 0);
            if (result == 0) {
                printf("✓ Successfully %s VSync using GLX_EXT_swap_control\n", enable ? "enabled" : "disabled");
                vsync_enabled = enable;
                return;
            } else {
                printf("❌ Failed to set VSync using GLX_EXT_swap_control (error: %d)\n", result);
            }
        }
    }
    
    // 检查并尝试使用 GLX_MESA_swap_control
    if (strstr(glx_ext, "GLX_MESA_swap_control")) {
        typedef int (*PFNGLXSWAPINTERVALMESAPROC)(unsigned int);
        PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA = 
            (PFNGLXSWAPINTERVALMESAPROC)glXGetProcAddress((const GLubyte*)"glXSwapIntervalMESA");
        if (glXSwapIntervalMESA) {
            int result = glXSwapIntervalMESA(enable ? 1 : 0);
            if (result == 0) {
                printf("✓ Successfully %s VSync using GLX_MESA_swap_control\n", enable ? "enabled" : "disabled");
                vsync_enabled = enable;
                return;
            } else {
                printf("❌ Failed to set VSync using GLX_MESA_swap_control (error: %d)\n", result);
            }
        }
    }
    
    // 检查并尝试使用 GLX_SGI_swap_control
    if (strstr(glx_ext, "GLX_SGI_swap_control")) {
        typedef int (*PFNGLXSWAPINTERVALSGIPROC)(int);
        PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = 
            (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddress((const GLubyte*)"glXSwapIntervalSGI");
        if (glXSwapIntervalSGI) {
            int result = glXSwapIntervalSGI(enable ? 1 : 0);
            if (result == 0) {
                printf("✓ Successfully %s VSync using GLX_SGI_swap_control\n", enable ? "enabled" : "disabled");
                vsync_enabled = enable;
                return;
            } else {
                printf("❌ Failed to set VSync using GLX_SGI_swap_control (error: %d)\n", result);
            }
        }
    }
    
    printf("❌ All VSync control methods failed\n");
    printf("Environment variable method: vblank_mode=%d ./x11-glx-test\n", enable ? 1 : 0);
    printf("========================\n");
}

// 完整的8x8像素字体渲染 - 支持ASCII字符32-127 (96个字符)
static const unsigned char font_8x8[128][8] = {
    // 控制字符 0-31 (使用空白或替代字符)
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 0 NUL
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 1 SOH
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 2 STX
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 3 ETX
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 4 EOT
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 5 ENQ
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 6 ACK
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 7 BEL
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 8 BS
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 9 TAB
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 10 LF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 11 VT
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 12 FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 13 CR
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 14 SO
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 15 SI
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 16 DLE
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 17 DC1
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 18 DC2
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 19 DC3
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 20 DC4
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 21 NAK
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 22 SYN
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 23 ETB
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 24 CAN
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 25 EM
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 26 SUB
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 27 ESC
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 28 FS
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 29 GS
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 30 RS
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 31 US
    
    // ASCII 可打印字符 32-127
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 32 SPACE
    {0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // 33 !
    {0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00}, // 34 "
    {0x66, 0x66, 0xFF, 0x66, 0xFF, 0x66, 0x66, 0x00}, // 35 #
    {0x18, 0x3E, 0x60, 0x3C, 0x06, 0x7C, 0x18, 0x00}, // 36 $
    {0x62, 0x66, 0x0C, 0x18, 0x30, 0x66, 0x46, 0x00}, // 37 %
    {0x3C, 0x66, 0x3C, 0x38, 0x67, 0x66, 0x3F, 0x00}, // 38 &
    {0x06, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // 39 '
    {0x0C, 0x18, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00}, // 40 (
    {0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00}, // 41 )
    {0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // 42 *
    {0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00}, // 43 +
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30}, // 44 ,
    {0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00}, // 45 -
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00}, // 46 .
    {0x00, 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00}, // 47 /
    
    // 数字 48-57 (0-9)
    {0x3C, 0x66, 0x6E, 0x76, 0x66, 0x66, 0x3C, 0x00}, // 48 0
    {0x18, 0x18, 0x38, 0x18, 0x18, 0x18, 0x7E, 0x00}, // 49 1
    {0x3C, 0x66, 0x06, 0x0C, 0x30, 0x60, 0x7E, 0x00}, // 50 2
    {0x3C, 0x66, 0x06, 0x1C, 0x06, 0x66, 0x3C, 0x00}, // 51 3
    {0x06, 0x0E, 0x1E, 0x66, 0x7F, 0x06, 0x06, 0x00}, // 52 4
    {0x7E, 0x60, 0x7C, 0x06, 0x06, 0x66, 0x3C, 0x00}, // 53 5
    {0x3C, 0x66, 0x60, 0x7C, 0x66, 0x66, 0x3C, 0x00}, // 54 6
    {0x7E, 0x66, 0x0C, 0x18, 0x18, 0x18, 0x18, 0x00}, // 55 7
    {0x3C, 0x66, 0x66, 0x3C, 0x66, 0x66, 0x3C, 0x00}, // 56 8
    {0x3C, 0x66, 0x66, 0x3E, 0x06, 0x66, 0x3C, 0x00}, // 57 9
    
    // 符号 58-64
    {0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00}, // 58 :
    {0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30}, // 59 ;
    {0x0E, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0E, 0x00}, // 60 <
    {0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00}, // 61 =
    {0x70, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x70, 0x00}, // 62 >
    {0x3C, 0x66, 0x06, 0x0C, 0x18, 0x00, 0x18, 0x00}, // 63 ?
    {0x3C, 0x66, 0x6E, 0x6E, 0x60, 0x62, 0x3C, 0x00}, // 64 @
    
    // 大写字母 65-90 (A-Z)
    {0x18, 0x3C, 0x66, 0x66, 0x7E, 0x66, 0x66, 0x00}, // 65 A
    {0x7C, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x7C, 0x00}, // 66 B
    {0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x00}, // 67 C
    {0x78, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0x78, 0x00}, // 68 D
    {0x7E, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x7E, 0x00}, // 69 E
    {0x7E, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x00}, // 70 F
    {0x3C, 0x66, 0x60, 0x6E, 0x66, 0x66, 0x3C, 0x00}, // 71 G
    {0x66, 0x66, 0x66, 0x7E, 0x66, 0x66, 0x66, 0x00}, // 72 H
    {0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00}, // 73 I
    {0x1E, 0x0C, 0x0C, 0x0C, 0x6C, 0x6C, 0x38, 0x00}, // 74 J
    {0x66, 0x6C, 0x78, 0x70, 0x78, 0x6C, 0x66, 0x00}, // 75 K
    {0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7E, 0x00}, // 76 L
    {0x63, 0x77, 0x7F, 0x6B, 0x63, 0x63, 0x63, 0x00}, // 77 M
    {0x66, 0x76, 0x7E, 0x7E, 0x6E, 0x66, 0x66, 0x00}, // 78 N
    {0x3C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00}, // 79 O
    {0x7C, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x00}, // 80 P
    {0x3C, 0x66, 0x66, 0x66, 0x6A, 0x6C, 0x36, 0x00}, // 81 Q
    {0x7C, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x00}, // 82 R
    {0x3C, 0x66, 0x60, 0x3C, 0x06, 0x66, 0x3C, 0x00}, // 83 S
    {0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00}, // 84 T
    {0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00}, // 85 U
    {0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00}, // 86 V
    {0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // 87 W
    {0x66, 0x66, 0x3C, 0x18, 0x3C, 0x66, 0x66, 0x00}, // 88 X
    {0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x00}, // 89 Y
    {0x7E, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x7E, 0x00}, // 90 Z
    
    // 符号 91-96
    {0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00}, // 91 [
    {0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x00}, // 92 \  // 
    {0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00}, // 93 ]
    {0x18, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00}, // 94 ^
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // 95 _
    {0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // 96 `
    
    // 小写字母 97-122 (a-z)
    {0x00, 0x00, 0x3C, 0x06, 0x3E, 0x66, 0x3E, 0x00}, // 97 a
    {0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x7C, 0x00}, // 98 b
    {0x00, 0x00, 0x3C, 0x60, 0x60, 0x60, 0x3C, 0x00}, // 99 c
    {0x06, 0x06, 0x3E, 0x66, 0x66, 0x66, 0x3E, 0x00}, // 100 d
    {0x00, 0x00, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00}, // 101 e
    {0x0E, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00}, // 102 f
    {0x00, 0x00, 0x3E, 0x66, 0x66, 0x3E, 0x06, 0x7C}, // 103 g
    {0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x00}, // 104 h
    {0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00}, // 105 i
    {0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x66, 0x3C}, // 106 j
    {0x60, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0x00}, // 107 k
    {0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00}, // 108 l
    {0x00, 0x00, 0x77, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // 109 m
    {0x00, 0x00, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x00}, // 110 n
    {0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x00}, // 111 o
    {0x00, 0x00, 0x7C, 0x66, 0x66, 0x7C, 0x60, 0x60}, // 112 p
    {0x00, 0x00, 0x3E, 0x66, 0x66, 0x3E, 0x06, 0x06}, // 113 q
    {0x00, 0x00, 0x7C, 0x66, 0x60, 0x60, 0x60, 0x00}, // 114 r
    {0x00, 0x00, 0x3E, 0x60, 0x3C, 0x06, 0x7C, 0x00}, // 115 s
    {0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x0E, 0x00}, // 116 t
    {0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3E, 0x00}, // 117 u
    {0x00, 0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00}, // 118 v
    {0x00, 0x00, 0x63, 0x6B, 0x7F, 0x3E, 0x36, 0x00}, // 119 w
    {0x00, 0x00, 0x66, 0x3C, 0x18, 0x3C, 0x66, 0x00}, // 120 x
    {0x00, 0x00, 0x66, 0x66, 0x66, 0x3E, 0x0C, 0x78}, // 121 y
    {0x00, 0x00, 0x7E, 0x0C, 0x18, 0x30, 0x7E, 0x00}, // 122 z
    
    // 符号 123-127
    {0x0E, 0x18, 0x18, 0x70, 0x18, 0x18, 0x0E, 0x00}, // 123 {
    {0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // 124 |
    {0x70, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x70, 0x00}, // 125 }
    {0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // 126 ~
    {0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00}, // 127 DEL
};

// 渲染文字到OpenGL
void render_text_opengl(const char* text, float x, float y, color_t color) {
    // 注意：调用本函数前应设置正交投影（如 glOrtho），否则字符可能不可见。
    if (!text) return;
    
    // 保存当前OpenGL状态
    glPushMatrix();
    
    // 设置文字颜色（使用无符号字节，范围0~255）
    glColor3ub(color.r, color.g, color.b);
    
    // 禁用深度测试以确保文字显示在最前面
    GLboolean depth_test_enabled = glIsEnabled(GL_DEPTH_TEST);
    if (depth_test_enabled) glDisable(GL_DEPTH_TEST);
    
    const char* ptr = text;
    float char_x = x;
    float char_y = y;
    
    // 计算字符在OpenGL坐标系中的大小
    float char_width = 8.0 / win_width *2.0f; // 每个字符的宽度
    float char_height = 8.0 / win_height *2.0f; // 每个字符的高度
    
    while (*ptr) {
        unsigned char font_index = (unsigned char)*ptr; // 直接使用ASCII值作为索引
        
        // 处理特殊字符
        if (*ptr == ' ') {
            char_x += char_width;
            ptr++;
            continue;
        } else if (*ptr == '\n') {
            char_x = x;
            char_y -= char_height * 1.5f; // 行间距
            ptr++;
            continue;
        } else if (*ptr == '\t') {
            char_x += char_width * 4; // Tab = 4个空格
            ptr++;
            continue;
        }
        
        // 确保索引在有效范围内
        if (font_index >= 128) {
            font_index = 32; // 超出范围的字符显示为空格
        }
        
        // 渲染字符 - 使用简单的点阵方式
        float pixel_width = char_width / 8.0f;   // 每个像素的宽度
        float pixel_height = char_height / 8.0f; // 每个像素的高度
        
        for (int row = 0; row < 8; row++) {
            unsigned char line = font_8x8[font_index][row];
            for (int col = 0; col < 8; col++) {
                if (line & (0x80 >> col)) {
                    // 绘制一个小矩形代表像素
                    float px = char_x + col * pixel_width;
                    float py = char_y - row * pixel_height;
                    
                    glBegin(GL_QUADS);
                    glVertex2f(px, py);
                    glVertex2f(px + pixel_width, py);
                    glVertex2f(px + pixel_width, py - pixel_height);
                    glVertex2f(px, py - pixel_height);
                    glEnd();
                }
            }
        }
        
        // 移动到下一个字符位置
        char_x += char_width;
        
        ptr++;
    }
    
    // 恢复深度测试状态
    if (depth_test_enabled) glEnable(GL_DEPTH_TEST);
    
    // 恢复矩阵状态
    glPopMatrix();
}

// 设置像素颜色（软件渲染）
void set_pixel(int x, int y, pixel_t pixel) {
    if (x >= 0 && x < win_width && y >= 0 && y < win_height) {
        // 翻转Y坐标以匹配X11坐标系
        int flipped_y = win_height - y;
        int index = (flipped_y * win_width + x);
        frame_buffer[index] = pixel;
    }
}

// 将文字渲染到软件缓冲区
void render_text_software(const char* text, int x, int y, color_t color) {    
    const char* ptr = text;
    int char_x = x;
    
    while (*ptr && char_x < win_width - 8) {
        unsigned char font_index = (unsigned char)*ptr; // 直接使用ASCII值作为索引
        
        // 处理特殊字符
        if (*ptr == ' ') {
            char_x += 8; // 空格宽度
            ptr++;
            continue;
        } else if (*ptr == '\n') {
            char_x = x;
            y -= 12; // 换行，向下移动
            ptr++;
            continue;
        } else if (*ptr == '\t') {
            char_x += 32; // Tab = 4个字符宽度
            ptr++;
            continue;
        }
        
        // 确保索引在有效范围内
        if (font_index >= 128) {
            font_index = 32; // 超出范围的字符显示为空格
        }
        
        // 渲染8x8字符 - 修正Y坐标以使文字正向显示
        for (int row = 0; row < 8; row++) {
            unsigned char line = font_8x8[font_index][row];
            for (int col = 0; col < 8; col++) {
                if (line & (0x80 >> col)) {
                    // 按X11坐标系处理Y坐标（set_pixel函数内部会处理坐标系转换）
                    set_pixel(char_x + col, y - row, color);
                }
            }
        }
        
        char_x += 8; // 移动到下一个字符位置
        ptr++;
    }
}

// 软件渲染初始化
void initSoftwareRenderer(int width, int height) {
    win_width = width;
    win_height = height;
    frame_buffer = (pixel_t *)calloc(win_width * win_height, sizeof(pixel_t)); // 分配RGB帧缓冲区
    if (!frame_buffer) {
        fprintf(stderr, "无法分配帧缓冲区内存\n");
        exit(1);
    }
}

// 清除帧缓冲区
void clear_buffer() {
    memset(frame_buffer, 0, win_width * win_height * sizeof(pixel_t));
}

// 软件渲染三角形（使用扫描线算法）
void render_triangle_software(vertex_t v1, vertex_t v2, vertex_t v3) {
    // 简单的三角形填充算法
    int x1 = (int)v1.x, y1 = (int)v1.y;
    int x2 = (int)v2.x, y2 = (int)v2.y;
    int x3 = (int)v3.x, y3 = (int)v3.y;
    unsigned char r1 = v1.color.r, g1 = v1.color.g, b1 = v1.color.b;
    unsigned char r2 = v2.color.r, g2 = v2.color.g, b2 = v2.color.b;
    unsigned char r3 = v3.color.r, g3 = v3.color.g, b3 = v3.color.b;

    int min_x = (x1 < x2) ? (x1 < x3 ? x1 : x3) : (x2 < x3 ? x2 : x3);
    int max_x = (x1 > x2) ? (x1 > x3 ? x1 : x3) : (x2 > x3 ? x2 : x3);
    int min_y = (y1 < y2) ? (y1 < y3 ? y1 : y3) : (y2 < y3 ? y2 : y3);
    int max_y = (y1 > y2) ? (y1 > y3 ? y1 : y3) : (y2 > y3 ? y2 : y3);
    
    for (int y = min_y; y <= max_y; y++) {
        for (int x = min_x; x <= max_x; x++) {
            // 使用重心坐标判断点是否在三角形内
            float denominator = (float)((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3));
            if (denominator == 0) continue;
            
            float a = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / denominator;
            float b = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / denominator;
            float c = 1 - a - b;
            
            if (a >= 0 && b >= 0 && c >= 0) {
                // 在三角形内，使用重心坐标插值颜色
                unsigned char r = (unsigned char)(a * r1 + b * r2 + c * r3);
                unsigned char g = (unsigned char)(a * g1 + b * g2 + c * g3);
                unsigned char bl = (unsigned char)(a * b1 + b * b2 + c * b3);
                set_pixel(x, y, (pixel_t){.r=r, .g=g, .b=bl});
            }
        }
    }
}

// 软件渲染压力测试
void render_software_stress_test() {
    clear_buffer();
    
    // 渲染100个小三角形，与OpenGL模式2保持一致
    for (int i = 0; i < 100; i++) {
        // 将OpenGL坐标转换为屏幕坐标，保持与OpenGL模式相同的布局
        float gl_x = (i % 10 - 4.5f) * 0.15f;  // OpenGL坐标 (-0.675 到 0.675)
        float gl_y = (i / 10 - 4.5f) * 0.15f;  // OpenGL坐标 (-0.675 到 0.675)
        
        // 转换为屏幕坐标（注意Y坐标系差异）
        int center_x = (int)(((gl_x + 1.0f) / 2.0f) * win_width);
        int center_y = (int)(((gl_y + 1.0f) / 2.0f) * win_height);  // 不翻转Y坐标
        
        // 计算三角形大小（对应OpenGL中的0.05单位）
        int size = (int)(0.05f * win_width / 2.0f);  // 相对于屏幕宽度的比例
        
        // 使用与OpenGL相同的颜色计算
        unsigned char r = (unsigned char)((float)(i % 3) / 2.0f * 255);
        unsigned char g = (unsigned char)((float)((i + 1) % 3) / 2.0f * 255);
        unsigned char b = (unsigned char)((float)((i + 2) % 3) / 2.0f * 255);
        
        // 渲染三角形，顶点朝上（与OpenGL一致）
        // OpenGL顶点：(x-0.05, y-0.05), (x+0.05, y-0.05), (x, y+0.05)
        color_t color = {.r = r, .g = g, .b = b};
        render_triangle_software(
            (vertex_t){center_x - size, center_y - size, color},
            (vertex_t){center_x + size, center_y - size, color},
            (vertex_t){center_x, center_y + size, color}
        );
    }
}

// 将软件渲染的结果显示到X窗口
void display_software_buffer() {
    // 获取显示信息
    int screen = DefaultScreen(display);
    Visual *visual = DefaultVisual(display, screen);
    int depth = DefaultDepth(display, screen);
    
    // 创建XImage，使用正确的参数
    XImage *image = XCreateImage(display, visual, depth, ZPixmap, 0,
                                (char*)frame_buffer, win_width, win_height,
                                32, win_width * sizeof(pixel_t));
    
    if (!image) {
        fprintf(stderr, "无法创建XImage，深度=%d，尝试其他格式\n", depth);
        
        // 如果32位失败，尝试24位
        image = XCreateImage(display, visual, 32, ZPixmap, 0,
                            (char*)frame_buffer, win_width, win_height,
                            32, win_width * 4);
    }
    
    if (!image) {
        fprintf(stderr, "无法创建任何格式的XImage\n");
        return;
    }
    
    // 设置字节序（重要！）
    if (ImageByteOrder(display) == LSBFirst) {
        image->byte_order = LSBFirst;
    } else {
        image->byte_order = MSBFirst;
    }
    image->bitmap_bit_order = LSBFirst;
    
    GC gc = DefaultGC(display, screen);
    XPutImage(display, win, gc, image, 0, 0, 0, 0, win_width, win_height);
    XFlush(display);
    
    // 安全释放XImage
    image->data = NULL; // 防止XDestroyImage释放我们的buffer
    XDestroyImage(image);
}

// 渲染多个三角形用于压力测试
void render_stress_test() {
    static float angle = 0.0f;
    angle += 1.0f; // 每帧增加1度
    
    glClear(GL_COLOR_BUFFER_BIT);
    
    // 保存当前矩阵状态
    glPushMatrix();
    
    // 应用旋转变换
    glRotatef(angle, 0.0f, 0.0f, 1.0f); // 绕Z轴旋转
    
    // 渲染多个小三角形来增加渲染负载
    for (int i = 0; i < 100; i++) {
        float x = (i % 10 - 4.5f) * 0.15f;
        float y = (i / 10 - 4.5f) * 0.15f;
        
        glBegin(GL_TRIANGLES);
        glColor3f((float)(i % 3) / 2.0f, (float)((i + 1) % 3) / 2.0f, (float)((i + 2) % 3) / 2.0f);
        glVertex2f(x - 0.05f, y - 0.05f);
        glVertex2f(x + 0.05f, y - 0.05f);
        glVertex2f(x, y + 0.05f);
        glEnd();
    }
    
    // 恢复矩阵状态
    glPopMatrix();
}

// 渲染单个三角形
void render_simple_triangle() {
    static float angle = 0.0f;
    angle += 1.0f; // 每帧增加1度
    
    glClear(GL_COLOR_BUFFER_BIT);
    
    // 保存当前矩阵状态
    glPushMatrix();
    
    // 应用旋转变换
    glRotatef(angle, 0.0f, 0.0f, 1.0f); // 绕Z轴旋转
    
    glBegin(GL_TRIANGLES);
    glColor3f(1.0f, 0.0f, 0.0f); // 红色
    glVertex2f(-0.6f, -0.6f);
    glColor3f(0.0f, 1.0f, 0.0f); // 绿色
    glVertex2f(0.6f, -0.6f);
    glColor3f(0.0f, 0.0f, 1.0f); // 蓝色
    glVertex2f(0.0f, 0.6f);
    glEnd();
    
    // 恢复矩阵状态
    glPopMatrix();
}

// 软件渲染单个三角形
void render_software_simple() {
    static float angle = 0.0f;
    angle += 1.0f; // 每帧增加1度
    
    clear_buffer();
    
    // 计算旋转后的顶点坐标
    float cos_a = cos(angle * M_PI / 180.0f);
    float sin_a = sin(angle * M_PI / 180.0f);
    
    // 原始顶点坐标
    float x1_orig = -0.6f, y1_orig = -0.6f;
    float x2_orig = 0.6f, y2_orig = -0.6f;
    float x3_orig = 0.0f, y3_orig = 0.6f;
    
    // 应用旋转变换
    float x1_rot = x1_orig * cos_a - y1_orig * sin_a;
    float y1_rot = x1_orig * sin_a + y1_orig * cos_a;
    
    float x2_rot = x2_orig * cos_a - y2_orig * sin_a;
    float y2_rot = x2_orig * sin_a + y2_orig * cos_a;
    
    float x3_rot = x3_orig * cos_a - y3_orig * sin_a;
    float y3_rot = x3_orig * sin_a + y3_orig * cos_a;
    
    // 将OpenGL坐标(-1到1)转换到屏幕坐标
    int x1 = (int)(((x1_rot + 1.0f) / 2.0f) * win_width);
    int y1 = (int)(((y1_rot + 1.0f) / 2.0f) * win_height);
    int x2 = (int)(((x2_rot + 1.0f) / 2.0f) * win_width);
    int y2 = (int)(((y2_rot + 1.0f) / 2.0f) * win_height);
    int x3 = (int)(((x3_rot + 1.0f) / 2.0f) * win_width);
    int y3 = (int)(((y3_rot + 1.0f) / 2.0f) * win_height);
    
    render_triangle_software(
        (vertex_t){x1, y1, RED},   // 红色
        (vertex_t){x2, y2, GREEN}, // 绿色
        (vertex_t){x3, y3, BLUE}    // 蓝色
    );
}


// OpenGL立方体渲染（简单旋转）
void render_opengl_cube() {
    static float angle = 0.0f;
    angle += 0.10f;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // 设置投影矩阵为透视
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    float aspect = (float)win_width / (float)win_height;
    float near = 0.1f, far = 10.0f, fov = 60.0f;
    float top = near * tanf(fov * 3.14159f / 360.0f);
    float bottom = -top;
    float right = top * aspect;
    float left = -right;
    glFrustum(left, right, bottom, top, near, far);

    // 设置模型视图矩阵
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -3.0f);
    glRotatef(angle, 1.0f, 1.0f, 0.0f);

    glBegin(GL_QUADS);
    // 前面
    glColor3f(1,0,0); glVertex3f(-0.5,-0.5,0.5); glVertex3f(0.5,-0.5,0.5); glVertex3f(0.5,0.5,0.5); glVertex3f(-0.5,0.5,0.5);
    // 后面
    glColor3f(0,1,0); glVertex3f(-0.5,-0.5,-0.5); glVertex3f(0.5,-0.5,-0.5); glVertex3f(0.5,0.5,-0.5); glVertex3f(-0.5,0.5,-0.5);
    // 左面
    glColor3f(0,0,1); glVertex3f(-0.5,-0.5,-0.5); glVertex3f(-0.5,-0.5,0.5); glVertex3f(-0.5,0.5,0.5); glVertex3f(-0.5,0.5,-0.5);
    // 右面
    glColor3f(1,1,0); glVertex3f(0.5,-0.5,-0.5); glVertex3f(0.5,-0.5,0.5); glVertex3f(0.5,0.5,0.5); glVertex3f(0.5,0.5,-0.5);
    // 上面
    glColor3f(0,1,1); glVertex3f(-0.5,0.5,0.5); glVertex3f(0.5,0.5,0.5); glVertex3f(0.5,0.5,-0.5); glVertex3f(-0.5,0.5,-0.5);
    // 下面
    glColor3f(1,0,1); glVertex3f(-0.5,-0.5,0.5); glVertex3f(0.5,-0.5,0.5); glVertex3f(0.5,-0.5,-0.5); glVertex3f(-0.5,-0.5,-0.5);
    glEnd();

    glDisable(GL_DEPTH_TEST);

    // 恢复为正交投影，适合2D渲染
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();    

}

// 软件渲染立方体（带深度缓冲遮蔽处理，二维投影）
void render_software_cube() {

    // 清空帧缓冲和深度缓冲
    clear_buffer();
    static float *zbuffer = NULL;
    static int zbuf_size = 0;
    int bufsize = win_width * win_height;
    if (!zbuffer || zbuf_size != bufsize) {
        if (zbuffer) free(zbuffer);
        zbuffer = (float*)malloc(sizeof(float) * bufsize);
        zbuf_size = bufsize;
    }
    for (int i = 0; i < bufsize; i++) zbuffer[i] = 1e30f;

    // 立方体顶点
    const float cube[8][3] = {
        {-0.5,-0.5,-0.5}, {0.5,-0.5,-0.5}, {0.5,0.5,-0.5}, {-0.5,0.5,-0.5},
        {-0.5,-0.5,0.5},  {0.5,-0.5,0.5},  {0.5,0.5,0.5},  {-0.5,0.5,0.5}
    };
    // 每面4顶点索引
    const int faces[6][4] = {
        {4,5,6,7}, // 前
        {0,1,2,3}, // 后
        {0,4,7,3}, // 左
        {1,5,6,2}, // 右
        {3,2,6,7}, // 上
        {0,1,5,4}  // 下
    };
    const color_t face_colors[6] = {
        {255,0,0,255}, {0,255,0,255}, {0,0,255,255}, {255,255,0,255}, {0,255,255,255}, {255,0,255,255}
    };
    // 旋转角度
    static float angle = 0.0f;
    angle += 0.10f;
    float ax = angle * 3.1415926f / 180.0f;
    float ay = angle * 3.1415926f / 360.0f;
    float ca = cosf(ax), sa = sinf(ax), cb = cosf(ay), sb = sinf(ay);
    // 投影参数
    float fov = 60.0f, zcam = 2.5f;
    float scale = win_height / (2.0f * tanf(fov*3.1415926f/360.0f));
    float proj[8][2], zview[8];
    for (int i = 0; i < 8; i++) {
        float x = cube[i][0], y = cube[i][1], z = cube[i][2];
        // Y轴旋转
        float rx = x*cb - z*sb;
        float rz = x*sb + z*cb;
        // X轴旋转
        float ry = y*ca - rz*sa;
        float rz2 = y*sa + rz*ca;
        float zz = rz2 + zcam;
        zview[i] = zz;
        proj[i][0] = win_width/2 + rx/zz*scale;
        proj[i][1] = win_height/2 - ry/zz*scale;
    }
    // 每面拆分为两个三角形
    for (int f = 0; f < 6; f++) {
        int idx[4];
        for (int k = 0; k < 4; k++) idx[k] = faces[f][k];
        int tris[2][3] = { {0,1,2}, {0,2,3} };
        for (int t = 0; t < 2; t++) {
            int i0 = idx[tris[t][0]], i1 = idx[tris[t][1]], i2 = idx[tris[t][2]];
            // 投影坐标
            float x0 = proj[i0][0], y0 = proj[i0][1], z0 = zview[i0];
            float x1 = proj[i1][0], y1 = proj[i1][1], z1 = zview[i1];
            float x2 = proj[i2][0], y2 = proj[i2][1], z2 = zview[i2];
            // 包围盒
            int minx = (int)fmaxf(0, floorf(fminf(fminf(x0, x1), x2)));
            int maxx = (int)fminf(win_width-1, ceilf(fmaxf(fmaxf(x0, x1), x2)));
            int miny = (int)fmaxf(0, floorf(fminf(fminf(y0, y1), y2)));
            int maxy = (int)fminf(win_height-1, ceilf(fmaxf(fmaxf(y0, y1), y2)));
            float denom = (y1-y2)*(x0-x2)+(x2-x1)*(y0-y2);
            if (fabsf(denom) < 1e-6f) continue;
            for (int y = miny; y <= maxy; y++) {
                for (int x = minx; x <= maxx; x++) {
                    float a = ((y1-y2)*(x-x2)+(x2-x1)*(y-y2))/denom;
                    float b = ((y2-y0)*(x-x2)+(x0-x2)*(y-y2))/denom;
                    float c = 1.0f - a - b;
                    if (a >= -0.01f && b >= -0.01f && c >= -0.01f) {
                        float z = a*z0 + b*z1 + c*z2;
                        int idxbuf = y*win_width + x;
                        if (z < zbuffer[idxbuf]) {
                            zbuffer[idxbuf] = z;
                            set_pixel(x, y, face_colors[f]);
                        }
                    }
                }
            }
        }
    }
}

// 更新FPS计算和模式字符串
void update_fps_and_mode_text() {
    frame_count++;
    double current_time = get_time();
    
    if (last_time == 0.0) {
        last_time = current_time;
    }
    
    double elapsed = current_time - last_time;
    if (elapsed >= 1.0) { // 每秒更新一次 FPS           
        current_fps = frame_count / elapsed;
        const char* mode_str;
        switch(test_mode) {
            case 1: mode_str = "OpenGL Simple"; break;
            case 2: mode_str = "OpenGL Stress"; break;
            case 3: mode_str = "Software Simple"; break;
            case 4: mode_str = "Software Stress"; break;
            case 5: mode_str = "OpenGL Cube"; break;
            case 6: mode_str = "Software Cube"; break;
            default: mode_str = "Unknown Mode"; break;
        }
        
        // 更新文字缓冲区
        snprintf(mode_text, sizeof(mode_text), "MODE: %s", mode_str);
        snprintf(fps_text, sizeof(fps_text), "FPS: %.1f", current_fps);
        snprintf(vsync_text, sizeof(vsync_text), "VSYNC: %s", vsync_enabled ? "ON" : "OFF");
        
        printf("[%s] FPS: %.2f (Frames: %d, Time: %.3fs)\n", 
               mode_str, current_fps, frame_count, elapsed);
        frame_count = 0;
        last_time = current_time;
    }
}

// 渲染UI文字信息
void render_ui_text() {
    int text_x = 10;
    int text_y_start = win_height - 10;  // 从顶部10像素开始
    int line_height = 15;   // 行间距15像素

    if (test_mode == 3 || test_mode == 4 || test_mode == 6) {
        // 软件渲染模式：在软件缓冲区中渲染文字
        // 统一文字位置：左上角开始，间距一致, 注意Y坐标翻转
        color_t color = {.b = 0, .g = 0, .r = 255};
        render_text_software(mode_text, text_x, text_y_start, color);
        render_text_software(fps_text, text_x, text_y_start - line_height, color);
        render_text_software(vsync_text, text_x, text_y_start - line_height * 2, color);
        render_text_software("RENDERING: Software (CPU)", text_x, text_y_start - line_height * 3, color);
        render_text_software("CONTROLS: 1-6 MODES V VSYNC Q QUIT", text_x, 20, color);
    } else {
        // OpenGL模式：使用OpenGL渲染文字
        // 转换为OpenGL坐标系，保持与软件渲染相同的相对位置
        float gl_text_x = text_x / (float)win_width * 2.0f - 1.0f; // 转换为OpenGL坐标系 (-1到1)
        float gl_text_y_start = text_y_start / (float)win_height * 2.0f - 1.0f;  // 从顶部开始
        float gl_line_height = line_height / (float)win_height * 2.0f;    // OpenGL坐标系中的行间距
        color_t color = {.b = 0, .g = 0, .r = 255};

        render_text_opengl(mode_text, gl_text_x, gl_text_y_start, color);
        render_text_opengl(fps_text, gl_text_x, gl_text_y_start - gl_line_height, color);
        render_text_opengl(vsync_text, gl_text_x, gl_text_y_start - gl_line_height * 2, color);
        render_text_opengl(renderer_text, gl_text_x, gl_text_y_start - gl_line_height * 3, color);
        render_text_opengl(rendering_type_text, gl_text_x, gl_text_y_start - gl_line_height * 4, color);
        render_text_opengl("CONTROLS: 1-6 MODES V VSYNC Q QUIT", gl_text_x, 20 / (float)win_height * 2.0f - 1.0f, color);
    }
}

// 管理VSync设置
void manage_vsync_settings() {
    // VSync设置只在OpenGL模式下生效
    if (test_mode == 1 || test_mode == 2) {
        static int last_vsync_state = -1;
        if (last_vsync_state != vsync_enabled) {
            if (check_vsync_support()) {
                set_vsync(vsync_enabled);
            }
            last_vsync_state = vsync_enabled;
        }
    }
}

// 主渲染函数
void render() {
    // 管理VSync设置
    manage_vsync_settings();
    
    // 根据测试模式渲染内容
    switch (test_mode) {
        case 1: // OpenGL简单模式
            render_simple_triangle();
            render_ui_text();            
            glXSwapBuffers(display, win);
            break;
        case 2: // OpenGL压力测试
            render_stress_test();
            render_ui_text(); 
            glXSwapBuffers(display, win);
            break;
        case 3: // 软件渲染简单模式
            render_software_simple();
            render_ui_text(); 
            display_software_buffer();
            break;
        case 4: // 软件渲染压力测试
            render_software_stress_test();
            render_ui_text(); 
            display_software_buffer();
            break;
        case 5: // OpenGL立方体
            render_opengl_cube();
            render_ui_text();
            glXSwapBuffers(display, win);
            break;
        case 6: // 软件渲染立方体
            render_software_cube();
            render_ui_text();
            display_software_buffer();
            break;
        default:
            printf("Unknown test mode: %d\n", test_mode);
            break;
    }
    
    // 更新FPS
    update_fps_and_mode_text();

}

// 事件循环
void eventLoop() {
    XEvent event;
    printf("==== OpenGL vs Software Rendering Performance Test ====\n");
    printf("Controls:\n");
    printf("  1 - OpenGL Simple Mode (Single Triangle)\n");
    printf("  2 - OpenGL Stress Test (100 Triangles)\n");
    printf("  3 - Software Simple Mode (Single Triangle)\n");
    printf("  4 - Software Stress Test (100 Triangles)\n");
    printf("  5 - OpenGL Cube\n");
    printf("  6 - Software Cube\n");
    printf("  v - Toggle VSync On/Off (OpenGL modes only)\n");
    printf("  q/ESC - Quit Program\n");
    printf("=====================================================\n");
    printf("Note: VSync only affects OpenGL modes (1-2)\n");
    printf("If VSync control is not supported, try:\n");
    printf("  vblank_mode=0 ./x11-glx-test  (disable VSync)\n");
    printf("  vblank_mode=1 ./x11-glx-test  (enable VSync)\n");
    printf("=====================================================\n");
    
    // 初始化文字缓冲区
    snprintf(mode_text, sizeof(mode_text), "MODE: OpenGL Simple");
    snprintf(fps_text, sizeof(fps_text), "FPS: 0.0");
    snprintf(vsync_text, sizeof(vsync_text), "VSYNC: %s", vsync_enabled ? "ON" : "OFF");
    
    while (1) {
        if (XPending(display) > 0) {
            XNextEvent(display, &event);
            if (event.type == Expose) {
                render();
            } else if (event.type == KeyPress) {
                KeySym key = XLookupKeysym(&event.xkey, 0);
                switch (key) {
                    case XK_1:
                        test_mode = 1;
                        printf("Switched to OpenGL Simple Mode\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_2:
                        test_mode = 2;
                        printf("Switched to OpenGL Stress Test\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_3:
                        test_mode = 3;
                        printf("Switched to Software Simple Mode\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_4:
                        test_mode = 4;
                        printf("Switched to Software Stress Test\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_5:
                        test_mode = 5;
                        printf("Switched to OpenGL Cube Mode\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_6:
                        test_mode = 6;
                        printf("Switched to Software Cube Mode\n");
                        frame_count = 0;
                        last_time = 0.0;
                        break;
                    case XK_v:
                        // 切换VSync状态
                        if (test_mode == 1 || test_mode == 2) {
                            if (check_vsync_support()) {
                                vsync_enabled = !vsync_enabled;
                                set_vsync(vsync_enabled);
                                printf("VSync %s in OpenGL mode\n", vsync_enabled ? "Enabled" : "Disabled");
                            } else {
                                printf("VSync control not supported. Use environment variable:\n");
                                printf("  vblank_mode=0 ./x11-glx-test  (disable)\n");
                                printf("  vblank_mode=1 ./x11-glx-test  (enable)\n");
                            }
                        } else {
                            printf("VSync is only available in OpenGL modes (1-2). Current mode: %d\n", test_mode);
                        }
                        break;
                    case XK_q:
                    case XK_Escape:
                        printf("Exiting program\n");
                        return;
                    default:
                        break;
                }
            }
        } else {
            // 如果没有事件，也渲染一次以确保画面更新
            render();
            //usleep(16667); // 约60FPS的延迟
        }
    }
}

// 清理资源
void cleanup() {
    if (frame_buffer) {
        free(frame_buffer);
        frame_buffer = NULL;
    }
    glXMakeCurrent(display, None, NULL);
    glXDestroyContext(display, glContext);
    XDestroyWindow(display, win);
    XCloseDisplay(display);
}

int main() {
    int width = 640;
    int height = 480;

    printf("=== OpenGL Diagnostics and Rendering Test ===\n");
    printf("Initializing X11 and OpenGL...\n\n");

    initXWindow(width, height);
    print_system_info(); // 显示系统信息
    initGL();
    // 检查VSync支持情况
    printf("=== VSync Support Check ===\n");
    if (check_vsync_support()) {
        printf("VSync control is available\n");
    } else {
        printf("VSync control is NOT available\n");
        printf("Will use environment variable method if needed\n");
    }
    printf("===========================\n");
    
    initSoftwareRenderer(width, height); // 初始化软件渲染器
    
    printf("Initialization complete! Starting render...\n\n");
    render(); // 添加初始渲染
    eventLoop();
    cleanup();

    return 0;
}

